const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
class UserController extends Controller {

    // 获取验证码
    async captcha() {
        const { ctx, service } = this;

        try {
            const captcha = await service.admin.generateCaptcha();
            ctx.body = {
                code: 0,
                data: captcha,
                msg: '获取验证码成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取验证码失败'
            };
        }
    }

    // 用户注册
    async register() {
        const { ctx, service } = this;

        try {
            const rules = {
                phone: { type: 'string', required: true },
                email: { type: 'string', required: true },
                password: { type: 'string', required: true },
            };

            ctx.validate(rules);

            const userData = ctx.request.body;
            const result = await service.user.register(userData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '注册成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '注册失败'
            };
        }
    }

    // 用户登录
    async login() {
        const { ctx, service } = this;

        try {
            // 参数验证
            const rules = {
                username: { type: 'string', required: true },
                password: { type: 'string', required: true },
                captchaId: { type: 'string', required: true }
            };

            ctx.validate(rules);

            const loginData = ctx.request.body;
            // 验证验证码
            await service.admin.verifyCaptcha(loginData.captchaId, loginData.captcha);

            const result = await service.user.login(loginData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '登录成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '登录失败'
            };
        }
    }

    // 获取用户列表
    async list() {
        const { ctx, service } = this;

        try {
            const query = ctx.query;

            // 设置分页参数默认值
            const page = parseInt(query.page) || 1;
            const pageSize = parseInt(query.pageSize) || 10;

            // 验证分页参数
            if (page < 1) {
                throw new Error('页码不能小于1');
            }
            if (pageSize < 1 || pageSize > 100) {
                throw new Error('每页数量必须在1-100之间');
            }

            const result = await service.user.getUsers({
                ...query,
                page,
                pageSize
            });

            ctx.body = {
                code: 0,
                data: result,
                msg: '获取成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取用户列表失败'
            };
        }
    }

    // 获取用户详情
    async detail() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            const user = await service.user.getUserById(id);

            ctx.body = {
                code: 0,
                data: user,
                msg: '获取成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取用户详情失败'
            };
        }
    }

    // 上传头像
    async uploadAvatar() {
        const { ctx, service } = this;

        try {
            console.log('收到头像上传请求');

            // 验证token
            const token = ctx.request.header.token;
            if (!token) {
                throw new Error('未提供token');
            }

            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
            const userId = decode.user_id;

            console.log('用户ID:', userId);

            // 获取上传的文件
            const file = ctx.request.files[0];
            if (!file) {
                throw new Error('请选择要上传的头像文件');
            }

            console.log('上传文件信息:', {
                filename: file.filename,
                filepath: file.filepath,
                mimeType: file.mimeType,
                size: file.size
            });

            // 验证文件类型
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!allowedTypes.includes(file.mimeType)) {
                throw new Error('只支持 jpg、png、gif、webp 格式的图片');
            }

            // 获取用户当前头像（用于删除旧文件）
            const user = await ctx.model.User.findByPk(userId);
            if (!user) {
                throw new Error('用户不存在');
            }

            const oldAvatar = user.avatar;
            console.log('用户当前头像:', oldAvatar);

            // 上传新头像
            const avatarUrl = await service.upload.uploadAvatar(file, userId);
            console.log('新头像URL:', avatarUrl);

            // 更新用户头像
            await user.update({
                avatar: avatarUrl,
                updated_at: new Date()
            });

            console.log('数据库更新成功');

            // 删除旧头像文件
            if (oldAvatar) {
                await service.upload.deleteOldAvatar(oldAvatar);
            }

            ctx.body = {
                code: 0,
                data: {
                    avatar: avatarUrl
                },
                msg: '头像上传成功'
            };

            console.log('头像上传完成');

        } catch (error) {
            console.error('头像上传错误:', error);

            // 清理临时文件
            if (ctx.request.files) {
                ctx.cleanupRequestFiles();
            }

            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '头像上传失败'
            };
        }
    }

    // 更新用户信息（确保包含avatar字段）
    async update() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;
            const updateData = ctx.request.body;

            // 验证路径参数
            const paramRules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(paramRules, ctx.params);

            // 验证body参数（添加avatar）
            const bodyRules = {
                nickname: { type: 'string', required: false },
                phone: { type: 'string', required: false },
                email: { type: 'string', required: false },
                avatar: { type: 'string', required: false },
                bio: { type: 'string', required: false },
                city: { type: 'string', required: false },
                company: { type: 'string', required: false },
                position: { type: 'string', required: false },
                gender: { type: 'number', required: false },
                address: { type: 'string', required: false },
            };
            ctx.validate(bodyRules);

            // 不允许更新密码（单独接口处理）
            if (updateData.password) {
                throw new Error('请使用修改密码接口');
            }

            const result = await service.user.updateUser(id, updateData);

            ctx.body = {
                code: 0,
                data: result,
                msg: '更新成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '更新用户信息失败'
            };
        }
    }

    // 删除用户
    async delete() {
        const { ctx, service } = this;

        try {
            const { id } = ctx.params;

            // 验证ID参数
            const rules = {
                id: { type: 'id', required: true }
            };
            ctx.validate(rules, ctx.params);

            await service.user.deleteUser(id);

            ctx.body = {
                code: 0,
                data: null,
                msg: '删除成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '删除用户失败'
            };
        }
    }

    // 获取当前登录用户信息
    async current() {
        const { ctx, service } = this;

        try {
            // 从token中获取用户ID
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            const user = await service.user.getCurrentUser(decode.user_id);

            ctx.body = {
                code: 0,
                data: user,
                msg: '获取成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '获取用户信息失败'
            };
        }
    }

    // 修改密码
    async changePassword() {
        const { ctx, service } = this;

        try {
            const rules = {
                oldPassword: { type: 'string', required: true },
                newPassword: { type: 'string', required: true }
            };
            ctx.validate(rules);

            const { oldPassword, newPassword } = ctx.request.body;

            // 从token中获取用户ID
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            // 获取用户并验证旧密码
            const user = await ctx.model.User.findByPk(decode.user_id);
            if (!user) {
                throw new Error('用户不存在');
            }

            if (user.password !== oldPassword) {
                throw new Error('原密码错误');
            }

            // 更新密码
            await user.update({
                password: newPassword,
                updated_at: new Date()
            });

            ctx.body = {
                code: 0,
                data: null,
                msg: '密码修改成功'
            };
        } catch (error) {
            if (error.errors) {
                ctx.body = {
                    code: 1,
                    data: null,
                    msg: `参数错误: ${error.errors[0].field} ${error.errors[0].message}`
                };
                return;
            }

            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '修改密码失败'
            };
        }
    }

    // 用户登出
    async logout() {
        const { ctx, service } = this;

        try {
            // 从token中获取用户ID（用于验证token有效性）
            const token = ctx.request.header.token;
            const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);

            // 调用服务层登出逻辑
            await service.user.logout();

            ctx.body = {
                code: 0,
                data: null,
                msg: '登出成功'
            };
        } catch (error) {
            ctx.body = {
                code: 1,
                data: null,
                msg: error.message || '登出失败'
            };
        }
    }
}

module.exports = UserController;